/**
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */
package org.jiopi.ibean.module.server.jiopi.rmi;

import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

import org.jiopi.remote.RemoteCentralConsole;
import org.jiopi.blueprint.server.Server;
import org.jiopi.framework.annotation.module.InstanceType;
import org.jiopi.framework.annotation.module.Instantiation;
import org.jiopi.framework.annotation.module.RegisterModule;
import org.jiopi.framework.annotation.module.SocketModule;


/**
 * 
 * @version 0.1.0.1  2012.8.12
 * @since 0.1.0.1  2012.8.12
 * @author netstarry
 *
 */
@RegisterModule
@Instantiation(type=InstanceType.CONFIGURATION_SINGLETON,initMethod="init")
public class JIOPiRMIServer implements Server {
	
	private int _rmiPort = 1099;
	
	@SocketModule(id="rcc",module="ibean.remote")
	private RemoteCentralConsole _rcc;
	
	private IbeanRemoteCentralConsoleRMI _rmircc;
	
	public void setRmiPort(int portNum){
		this._rmiPort = portNum;
	}
	
	public void setRemoteCentralConsole(RemoteCentralConsole rcc){
		this._rcc = rcc;
	}
	
	public void init(){
		_rmircc = new IbeanRemoteCentralConsoleRMI(_rcc);
	}

	/**
	 * RMI Server CAN NOT shutdown
	 */
	@Override
	public void shutdown() {
		
	}

	/**
	 * start the RMI server using specified configuration
	 */
	@Override
	public void start() throws RuntimeException{
		System.out.println("JIOPi RMI Server starting...");
		try {
			_rmircc.setContextClassLoader(Thread.currentThread().getContextClassLoader());
			Remote stub = UnicastRemoteObject.exportObject(_rmircc, 0);
			Registry registry = LocateRegistry.createRegistry(_rmiPort);
			registry.rebind("jiopi.remote", stub);
		} catch (RemoteException e) {
			throw new RuntimeException(e);
		}
		System.out.println("JIOPi RMI Server start finished.");		
	}

}
